package intranet.client;

/**
 * @author Baptiste RENDU
 * @author Robin TROADEC
 */

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Point d'entrée du programme.
 */
public class Intranet_grpc implements EntryPoint {
	
	private final ConnexionServiceAsync connexionService = GWT
			.create(ConnexionService.class);
	
	private Session session=new Session();
	private FileTree fileTree;
	private Tabs tabs;
	private TemplatesTab template;
	private AdminTab admin;
	private Calendar cal;
	private ShareTab shareDoc;
	private ProfileTab profil;

	private SimulatorTab simulator;

	private VerticalPanel gadgetPanel,treePanel;

	
	@Override
	public void onModuleLoad() {
		Window.addResizeHandler(new ResizeHandler() {
			
			@Override
			public void onResize(ResizeEvent event) {
				// TODO Auto-generated method stub
				fileTree.setSize(Window.getClientWidth()*2/10+"px",Window.getClientHeight()*2/5+"px");
				tabs.setSize(Window.getClientWidth()*16/20,Window.getClientHeight()*9/10);
				//template.onResize();
				//admin.onResize();
			}
		});
		init();
	}
	
	/**
	 * fonction qui verifie les cookies et demande une validation des identifiants
	 */
	public void init()
	{
		session.add("sessionId",Cookies.getCookie("session_intranet"));
		validateSession();
	}
	/**
	 * affiche le panneau de login et demande les verification au serveur
	 */
	public void notLogged()
	{
		RootPanel.get().clear();
		session.clear();
		
		final DecoratorPanel decoLoginPanel = new DecoratorPanel();
		decoLoginPanel.addStyleName("loginPanel");
		final VerticalPanel loginPanel= new VerticalPanel();
			loginPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		final HorizontalPanel hPanelLogin = new HorizontalPanel();
		hPanelLogin.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		final ValidTextBox loginTextBox= new ValidTextBox();
		Label ident= new Label("Identifiant");
			ident.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
			ident.setWidth("100px");
		hPanelLogin.add(ident);
		hPanelLogin.add(loginTextBox);
	    
	    
	    // Add a normal password text box
	    final HorizontalPanel hPanelPassword = new HorizontalPanel();
	    final PasswordTextBox passwordTextBox= new PasswordTextBox();
	    Label mdp = new Label("Mot de passe");
	    	mdp.setWidth("100px");
	    	mdp.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
	    hPanelPassword.add(mdp);
	    hPanelPassword.add(passwordTextBox);

	    final Label error=new Label();
	    
	    final PushButton valid= new PushButton("Connexion");
	    //valid.setSize("160px","30px");
	    
	    loginPanel.add(hPanelLogin);
	    loginPanel.add(hPanelPassword);
	    loginPanel.add(valid);
	    loginPanel.add(error);
	    decoLoginPanel.add(loginPanel);
	    RootPanel.get().add(decoLoginPanel);
	    loginTextBox.addKeyPressHandler(new KeyPressHandler() {
			
			@Override
			public void onKeyPress(KeyPressEvent event) {
				// TODO Auto-generated method stub
				if (event.getNativeEvent().getKeyCode()==KeyCodes.KEY_ENTER)
				{
					connexionService.getSession(loginTextBox.getText(), passwordTextBox.getText(), new AsyncCallback<Session>() {	
						@Override
						public void onSuccess(Session result) {
							if(result!=null)
							{
									session.setSession(result);// TODO Auto-generated method stub
									Cookies.setCookie("session_intranet",result.get("sessionId"));
									logged();
							}
						}
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							error.setText("Problème de connection au serveur");
						}
					});
				}
			}
		});
	    passwordTextBox.addKeyPressHandler(new KeyPressHandler() {
			
			@Override
			public void onKeyPress(KeyPressEvent event) {
				// TODO Auto-generated method stub
				if (event.getNativeEvent().getKeyCode()==KeyCodes.KEY_ENTER)
				{
					connexionService.getSession(loginTextBox.getText(), passwordTextBox.getText(), new AsyncCallback<Session>() {	
						@Override
						public void onSuccess(Session result) {
							if(result!=null)
							{
									session.setSession(result);// TODO Auto-generated method stub
									Cookies.setCookie("session_intranet",result.get("sessionId"));
									logged();
							}
						}
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							error.setText("Problème de connection au serveur");
						}
					});
				}
			}
		});
	    valid.addClickHandler(new ClickHandler() {	
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				connexionService.getSession(loginTextBox.getText(), passwordTextBox.getText(), new AsyncCallback<Session>() {	
					@Override
					public void onSuccess(Session result) {
						if(result!=null)
						{
								session.setSession(result);// TODO Auto-generated method stub
								Cookies.setCookie("session_intranet",result.get("sessionId"));
								logged();
						}
					}
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						error.setText("Problème de connection au serveur");
					}
				});
			}
		});  
	}

	/**
	 * Fonction qui permet de charger l'interface une fois connecté
	 */
	public void logged()
	{
		HorizontalPanel panel = new HorizontalPanel();
		RootPanel.get().clear();
	 PushButton disconnect = new PushButton("se déconnecter");
	 disconnect.addStyleName("backBlueWhite");
		disconnect.addClickHandler(new ClickHandler() {	
			
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				disconnect();
			}
		});
		
		gadgetPanel = new VerticalPanel();
		gadgetPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT);
		treePanel = new VerticalPanel();
		treePanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT);
		
		tabs = new Tabs(1.5,Unit.EM);
		
		
		fileTree = new FileTree(session.get("teacher_login"),tabs.getViewerTab());
		cal = new Calendar(session);

		
		
		template = new TemplatesTab(session);
		tabs.add(template,"Modèles");
		
		if (!session.get("teacher_status").equals("-1"))
		{
			simulator = new SimulatorTab(session);
			tabs.add(simulator,"Bac à sable");
		}
		

		shareDoc = new ShareTab(session);
		tabs.add(shareDoc,"Partage des documents");
		
		profil = new ProfileTab(session);
		tabs.add(profil,"Mon Profil");

		
		if (session.get("teacher_status").equals("0"))
		{
			admin = new AdminTab(session);
			tabs.add(admin,"Administration");
		}
	
		
		treePanel.add(fileTree);
		gadgetPanel.add(treePanel);
		
		gadgetPanel.add(cal);
		
		panel.add(gadgetPanel);
		panel.add(tabs);
		fileTree.setSize(Window.getClientWidth()*2/10+"px",Window.getClientHeight()*2/5+"px");
		tabs.setSize(Window.getClientWidth()*16/20,Window.getClientHeight()*9/10);
		RootPanel.get().add(panel);  
		RootPanel.get("disconnect").add(disconnect);
	}

	/**
	 * permet de valider une session par une requete au servlet
	 */
    private void validateSession(){	
    	connexionService.validate(new AsyncCallback<Session>() {
			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);
			}
			@Override
			public void onSuccess(Session result) {
				if (!session.get("sessionId")
						.equals(result.get("sessionId"))|| session.get("sessionId").isEmpty()|| session.get("sessionId")==null) {
					session.clear();
					notLogged();
				} else if (session.get("sessionId").equals(result.get("sessionId"))) {
					session.setSession(result);
					logged();
				}
			}
		});
    }
    /**
	 * permet de detruire la session de l'utilisateur coté client et serveur
	 */
    public void disconnect()
    {
    	Cookies.removeCookie("session_intranet");
    	session.clear();
    	connexionService.invalidate(new AsyncCallback<Boolean>() {
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onSuccess(Boolean result) {
				// TODO Auto-generated method stub
				init();
			}
		});
    	
    	RootPanel.get("disconnect").clear();
    }
}
